import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useRef, useState } from 'react';
import { message, UploadProps, Spin, Upload } from 'antd';
import { onCloseModalCommon, getTenant } from '@/utils';
import { AssetChangeManageAPI } from '../common/type';
import { AssetListManageContext } from './useManageContext';
import { IAssetListActionEnum } from './useManageReducer';
import { getRequestIp } from '../../Acommon';
import { InboxOutlined } from '@ant-design/icons';

export const OpenUploadModal: React.FC<AssetChangeManageAPI.IOpenMaterialModal> = ({ curRes, isShowModal, onClose }) => {
  /** 弹框的ref */
  const uploadModalRef: Ref<IOneModalRef> = useRef(null);
  const { styleFixCls, assetForm, assetListDispatch } = useContext(AssetListManageContext);
  const baseUrl = getRequestIp();
  const [upLoading, setUpLoading] = useState<boolean>(false);
  const [applyChangeInfoList, setApplyChangeInfoList] = useState([]);

  /* 上传 */
  const uploadProps: UploadProps = {
    accept: '.xls,.xlsx',
    headers: {
      tenantName: getTenant(),
    },
    name: 'attachFile',
    maxCount: 1,
    action: `${baseUrl}/assetApplyChange/importChange/${assetForm?.getFieldValue('changeType')}`,
    onChange(info) {
      if (info.file.status == 'uploading') {
        setUpLoading(true);
      }
      if (info.file.status === 'done') {
        if (info.file?.response) {
          if (info.file?.response?.msgFlag) {
            message.success(`${info.file.name} 上传成功`);
            if (info.file?.response?.obj) {
              setApplyChangeInfoList(info.file?.response?.obj);
              // onUploadCancel()
              // setDetailId(info.file?.response?.obj)
              // reloadManage()
              // info.file?.response?.obj.map((item, index) => {
              //   item.rowId = `${new Date().getTime()}${index}`;
              //   return item;
              // });
              // onSetUploadInfo(info.file?.response?.obj);
            }
            setUpLoading(false);
          } else {
            message.error(<pre>{info.file?.response?.msg || '导入失败'}</pre>);
            setUpLoading(false);
          }
        }
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
        // onResetUpload();
        setUpLoading(false);
      }
    },
  };

  /** 初始化 */
  // useEffect(() => {}, [isShowModal]);

  /** 点击确定 */
  const onSave = () => {
    if (applyChangeInfoList?.length > 300) return message.warning('导入数据最多300条');
    if (upLoading) return message.warning('文件上传中请稍等!');
    if (applyChangeInfoList?.length == 0) return message.warning('导入数据至少1条');
    assetListDispatch({
      type: IAssetListActionEnum.SELECT_ASSET,
      payload: applyChangeInfoList,
    });
    onCloseModalCommon(uploadModalRef);
  };

  return (
    <>
      <OneModal
        open={true}
        getContainer={false}
        ref={uploadModalRef}
        title={'导入'}
        onCancel={onClose}
        width={document.body.clientWidth * 0.45}
        bodyStyle={{
          height: document.body.clientHeight * 0.35,
          padding: 10,
        }}
        onOk={onSave}
      >
        <Spin spinning={upLoading}>
          <div className={'download'} style={{ width: '100%', height: '70%' }}>
            <Upload.Dragger {...uploadProps} className={'dragger'} style={{ width: '100%', height: '70%' }}>
              <div style={{ height: 'auto' }}>
                <p className="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <div className={'upload-text'}>
                  将文件拖到此处，或&nbsp;
                  <span className={'upload-text-click'}>点击上传</span>
                </div>
              </div>
            </Upload.Dragger>
            <div className={styleFixCls + 'tip-title'} slot="tip">
              • 文件格式保证正确（仅支持.xlsx .xls文件）
            </div>
          </div>
        </Spin>
      </OneModal>
    </>
  );
};
